package com.itheima.controller;


import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public Result page(StudentQueryParam studentQueryParam){
        log.info("条件分页查询：{}",studentQueryParam);
       PageResult<Student> pageResult =  studentService.page(studentQueryParam);
       return Result.success(pageResult);
    }

    @PostMapping
    public Result insert(@RequestBody Student student){
        log.info("添加学员{}",student);
        studentService.insert(student);
        return Result.success();
    }

    @GetMapping("/{id:\\d+}")
    public Result getById(@PathVariable Integer id){
        log.info("查询id为{}的学员",id);
        Student student = studentService.getById(id);
        return Result.success(student);
    }

    @PutMapping
    public Result update(@RequestBody Student student){
        log.info("修改学员{}",student);
        studentService.update(student);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids){
        List<Integer> idList = Arrays.stream(ids.split(","))
                .map(Integer::parseInt)  // 转换为整数
                .collect(Collectors.toList());
        log.info("批量删除学员{}",ids);
        studentService.delete(idList);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result score(@PathVariable Integer id,@PathVariable Integer  score){
        log.info("给id为{}的违纪学员加{}分",id,score);
        studentService.score(id,score);
        return Result.success();
    }

}
